import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken ,removeInfo,removeToken,} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {

  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  let toPaths = null

  if (hasToken) {
    // console.log(hasToken);
    window.onbeforeunload = function(){
      // console.log("又刷新",to.path);

      localStorage.removeItem("active")

      if(to.path != "/404"){ //保存刷新前浏览的页面
        let path = JSON.stringify(to.path)
        localStorage.setItem("active",path)
      }
    }
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: store.state.app.menuList[0].path })

      NProgress.done()

    }else {
      if(store.state.app.isFresh == true){  //如果刷新页面  调获取菜单接口 获取菜单进行渲染  不能存在本地
        
        let activeMenu = JSON.parse(localStorage.getItem("active"))

        store.dispatch("app/getMenu").then(()=>{

          if(activeMenu ){ //读取本地是否有上次浏览的菜单
            toPaths = activeMenu
          }else{
            toPaths =  store.state.app.menuList[0].path
          }

          next({ path: toPaths ,replace:true})

          localStorage.removeItem("active")
        })
        .catch(()=>{
          Message.error("获取角色菜单失败!")
          removeInfo(),
          removeToken()
          next('/login')
        })
        // next({...to,replace:true})
      } else{

        next()
      }
      NProgress.done()
    }
  } else {
      
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      Message.error("登陆超时,请重新登陆!")
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
